package com.aqie.libfactory.presenter.account;

import android.text.TextUtils;

import com.aqie.libcommon.factory.data.DataSource;
import com.aqie.libcommon.factory.presenter.BasePresenter;
import com.aqie.libfactory.data.helper.AccountHelper;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.account.AccountRspModel;
import com.aqie.libfactory.model.api.account.LoginModel;

import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 登录逻辑
 */
public class LoginPresenter extends BasePresenter<LoginContract.View>
        implements LoginContract.Presenter, DataSource.Callback<AccountRspModel> {
    public LoginPresenter(LoginContract.View view) {
        super(view);
    }

    @Override
    public void onDataLoaded(AccountRspModel user) {
        final LoginContract.View view = getView();
        if (view == null)
            return;
        // 强制执行在主线程中
        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.loginSuccess();
            }
        });
    }


    @Override
    public void login(String phone, String code, String deviceId) {
        start();

        final LoginContract.View view = getView();

        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(code)) {
            view.showError("手机号或验证码不能为空！");
        } else {
            // 尝试传递PushId
            LoginModel model = new LoginModel(phone, code, deviceId);
            AccountHelper.login(model, this);
        }
    }

    @Override
    public void onDataNotAvailable(final String errMsg) {
        // 网络请求告知注册失败
        final LoginContract.View view = getView();
        if (view == null)
            return;
        // 此时是从网络回送回来的，并不保证处于主现场状态
        // 强制执行在主线程中
        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                // 调用主界面注册失败显示错误
                view.showError(errMsg);
            }
        });
    }

    private static class LoginSmsCallback implements Callback<RspModel<String>> {
        final DataSource.Callback<String> callback;

        LoginSmsCallback(DataSource.Callback<String> callback) {
            this.callback = callback;
        }
        @Override
        public void onResponse(Call<RspModel<String>> call, Response<RspModel<String>> response) {
            RspModel<String> rspModel = response.body();
            if (rspModel!=null && rspModel.success()){
                String smsCode = rspModel.getData();
                if (callback != null)
                    callback.onDataLoaded(smsCode);
            }
        }

        @Override
        public void onFailure(Call<RspModel<String>> call, Throwable t) {

        }
    }
}
